package com.snts.synchronization.schema;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.sql.Types;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.snts.synchronization.core.BaseTable;
import com.snts.synchronization.core.Column;
import com.snts.synchronization.core.SyncTable;
import com.snts.synchronization.core.Column.SyncDirection;

public class TriggerGenerator {

	private static final int[] types = new int[] { Types.ARRAY, Types.BIGINT, Types.BINARY, Types.BIT, Types.BLOB, Types.BOOLEAN,
			Types.CHAR, Types.CLOB, Types.DATE, Types.DECIMAL, Types.DOUBLE, Types.FLOAT, Types.INTEGER, Types.LONGNVARCHAR,
			Types.LONGVARBINARY, Types.LONGVARCHAR, Types.NCHAR, Types.NCLOB, Types.NUMERIC, Types.NVARCHAR, Types.REAL, Types.SMALLINT,
			Types.TIME, Types.TIMESTAMP, Types.TINYINT, Types.VARBINARY, Types.VARCHAR };

	private static final String[] type_names = new String[] { "T_ARRAY", "T_BIGINT", "T_BINARY", "T_BIT", "T_BLOB", "T_BOOLEAN", "T_CHAR",
			"T_CLOB", "T_DATE", "T_DECIMAL", "T_DOUBLE", "T_FLOAT", "T_INTEGER", "T_LONGNVARCHAR", "T_LONGVARBINARY", "T_LONGVARCHAR",
			"T_NCHAR", "T_NCLOB", "T_NUMERIC", "T_NVARCHAR", "T_REAL", "T_SMALLINT", "T_TIME", "T_TIMESTAMP", "T_TINYINT", "T_VARBINARY",
			"T_VARCHAR" };

	public static String generate(BaseTable table) throws IOException {
		if (SchemaUpdatesGenerator.ts > 0) {
			VelocityContext context = new VelocityContext();
			context.put("table", table);
			context.put("SD_INSIDE", SyncDirection.SD_INSIDE);
			context.put("SD_OUTSIDE", SyncDirection.SD_OUTSIDE);
			context.put("SD_BOTH", SyncDirection.SD_BOTH);
			for (int i = 0; i < types.length; i++) {
				context.put(type_names[i], types[i]);
			}

			return Utils.evaluateTemplateFromResource(TriggerGenerator.class, "triggerGenerator.tpl", context);
		}
		return null;
	}

	public static void main(String[] args) throws IOException {
		SyncTable table = new SyncTable();
		table.setSchema("schema1");
		table.setName("table1");
		Column col = new Column();
		col.setName("col1");
		col.setSyncDirection(SyncDirection.SD_INSIDE);
		table.addColumn(col);

		col = new Column();
		col.setName("col2");
		col.setSyncDirection(SyncDirection.SD_OUTSIDE);
		table.addColumn(col);

		col = new Column();
		col.setName("col3");
		col.setSyncDirection(SyncDirection.SD_BOTH);
		table.addColumn(col);
		for (int i = 0; i < types.length; i++) {
			System.out.println(type_names[i] + "=" + types[i]);
		}

		// System.out.println(generate(table));
	}

}
